//: -L+wsock32.lib+Advapi32.lib+cares.lib+dares.lib+IPHlpAPI  -I..

import
	dares.Types ,
	tango.io.Console ,
	tango.io.Stdout  ;

void main() {
	
	dump_c();
	Stdout.flush;
}




void dump_c() {
	
	_Struct.Load!(ares_addrttl)();
	_Struct.Load!(ares_addr6ttl)();
	_Struct.Load!(ares_srv_reply)();
	_Struct.Load!(ares_mx_reply)();
	_Struct.Load!(ares_txt_reply)();
	
	_Struct.Load!(ares_options)();
	_Struct.Load!(ares_addr_node)(["addr4", "addr6"]);
	
	_Struct.Load!(list_node)();
	_Struct.Load!(apattern)();
	_Struct.Load!(ares_channeldata)();
	
	_Struct.Dump ;
	_Struct.GenTest ;
}


void test_c(){
	auto ret	= ares_library_init(ARES_LIB_INIT_ALL);
	if ( ret  != ARES_SUCCESS) {
		printf( "ares_library_init: %d %s\n", ret, ares_strerror(ret) );
	}
	
	ares_channel	channel  ;
	ret	= ares_init(&channel) ;
	if (ret != ARES_SUCCESS) {
		printf( "ares_init_options: %d %s\n", ret, ares_strerror(ret) );
		return ;
	}
	
	ares_query(channel, "163.com\0".ptr, ns_c_in , ns_t_a, &my_cb, null );
	//ares_query(channel, "gmail.com\0".ptr, ns_c_in , ns_t_mx, &my_cb, null );
	
	timeval  tv;
	timeval *tvp;
	auto read_fds	= new SocketSet();
	auto write_fds	= new SocketSet();
	while(true){
		read_fds.reset ;
		write_fds.reset ;
		auto nfds	= ares_fds(channel , read_fds.toFd_set, write_fds.toFd_set);
		if (nfds == 0) {
			Stdout.formatln("break:{}", __LINE__ );
			break;
		}
		tvp	= ares_timeout(channel, NULL, &tv);
		auto count	= SocketSet.select(read_fds, write_fds , null, tvp);
		if (count < 0 ) {	// && SOCKERRNO != EINVAL
			Stdout.formatln("break:{}", __LINE__ );
		 	break;
		}
		ares_process(channel, read_fds.toFd_set, write_fds.toFd_set );
	}
	
	ares_destroy(channel);
	ares_library_cleanup();
}


extern(C) void my_cb(void *arg,  int status, int timeouts, ubyte *abuf, int alen){
	
	// File.set(`dns.bin`, abuf[0..alen] );
	auto tmp	= cast(ubyte[]) File.get(`dns.bin`);
	abuf	= &tmp[0];
	alen	= tmp.length ;
	
	auto dq	= DNS_Query.Load(abuf, alen);
	
	dq.h.dump ;
	
	foreach( q; dq.q){
		q.dump() ;
	}
	
	foreach( r; dq.an ){
		r.dump ;
		r.dump_ptr("\t\t") ;
	}
	foreach( r; dq.ns ){
		r.dump ;
		r.dump_ptr("\t\t") ;
	}
	foreach( r; dq.ar ){
		r.dump ;
		r.dump_ptr("\t\t") ;
	}
	
}


